package cn.huanghuai.reggie.service.impl;

import cn.huanghuai.reggie.dto.DishDto;
import cn.huanghuai.reggie.entity.Dish;
import cn.huanghuai.reggie.entity.DishFlavor;
import cn.huanghuai.reggie.mapper.DishMapper;
import cn.huanghuai.reggie.service.DishFlavorService;
import cn.huanghuai.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品同时保存口味数据
     * 因为操作多张表，所以要加上事务控制 @Transactional
     *  同时要开启事务支持
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基础信息
        this.save(dishDto);

        //已经执行了保存操作，可以通过dishDto中获得菜品的id
        Long dishId = dishDto.getId();

        //准备为菜品口味附上对应的菜品id
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) ->{
           item.setDishId(dishId);
           return item;
        }).collect(Collectors.toList());

        //保存菜品口味到菜品口味表
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息，从dish表查询
        Dish dish = this.getById(id);

        //查询菜品对应的口味信息
            //查询条件构造器
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //添加查询条件
        lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            //执行查询
        List<DishFlavor> flavors = dishFlavorService.list(lambdaQueryWrapper);

        //封装、拷贝信息到DishDto中并返回数据
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavors);
        return dishDto;
    }
}
